<?php

namespace App\Http\Controllers\Backstage;

use App\Http\Controllers\Backstage\BCommonController;
use Illuminate\Http\Request;
use App\Models\PictureModel;
use App\Models\CommonModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Session;
class PictureController extends BCommonController
{
    protected $redirectTo = '/backstage/picture/index';
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $list = DB::table('picture')->where(['status'=>0])->orderBy('sort_order','DESC')->orderBy('id','DESC')->paginate(15);
        // dd($list);
        return view('backstage/picture/index',compact('list'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function add()
    {
        return view('backstage/picture/add');
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function doadd(Request $request)
    {
        if( $request->isMethod('POST') ){
            $info = $request->except('_token');
            $file = $request->file('img_url');
            if(empty($info->name)){
                return json_encode(array('status' => 0, 'message'=>'圖片標題不能為空！'));
            }
            if( $file !== null ){
                if ($file->isValid())
                {
                    // 獲取文件相關信息
                    $originalName = $file->getClientOriginalName(); // 文件原名
                    $ext = $file->getClientOriginalExtension();     // 擴展名
                    $imagesType = ['jpg','jpeg','gif','bmp','png'];
                    if(!in_array($ext,$imagesType)){
                        return response()->json(array('status' => 0,'message'=>'不允許上傳的文件類型'));
                    }
                    $size=$file->getSize();
                    if($size>2*1024*1024){
                        return response()->json(array('status' => 0,'message'=>'文件過大，推薦圖片大小：2M'));
                    }
                    $realPath = $file->getRealPath();   //臨時文件的絕對路徑
                    $type = $file->getClientMimeType();     // image/jpeg
                    // 上傳文件
                    $filename = date('YmdHis') . '-' . uniqid() . '.' . $ext;
                    // 將圖片URL保存到數據庫                                    
                    $data['img_url'] = '/uploads/picture/'.$filename;

                    // 使用我們新建的uploads本地存儲空間（目錄）
                    $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
                    if($bool!=true){
                        return json_encode(array('status' => 0, 'message'=>'圖片上傳失敗'));
                    }
                    // else{
                    //     return json_encode(array('status' => 1, 'message'=>'圖片上傳成功'));
                    // }
                }                       
            }else{
                return json_encode(['status' => 0, 'message'=>'請選擇要上傳的圖片']);
            }
            $data['name'] = trim($info['name']);
            $data['desc'] = trim($info['desc']);
            $data['is_show'] = intval($info['is_show']);
            $newid = CommonModel::addDataGetId('picture',$data);
            if($newid){
                return json_encode(['status' => 1, 'message'=>'添加成功','jumpUrl'=>$this->redirectTo]);
            }else{
                return json_encode(['status' => 0, 'message'=>'添加失敗']);
            }
        }
    }

    public function edit($id)
    {
        $data = CommonModel::getOne('picture',['id'=>$id]);
        return view('backstage/picture/edit',['data'=>$data]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function doedit(Request $request, $id)
    {
        if( $request->isMethod('POST') ){     
            $info = $request->except('_token'); 
            $file = $request->file('img_url');  
            if(empty($info['name'])) return json_encode(array('status' => 0, 'message'=>'圖片標題不能為空！'));
            if(empty($info['id'])) return json_encode(['status' => 0, 'message'=>'未能獲取文章ID']);
              
            if( $file !== null ){
                if ($file->isValid())
                {
                    // 獲取文件相關信息
                    $originalName = $file->getClientOriginalName(); // 文件原名
                    $ext = $file->getClientOriginalExtension();     // 擴展名
                    $imagesType = ['jpg','jpeg','gif','bmp','png'];
                    if(!in_array($ext,$imagesType)){
                        return response()->json(array('status' => 0,'message'=>'不允許上傳的文件類型'));
                    }
                    $size=$file->getSize();
                    if($size>2*1024*1024){
                        return response()->json(array('status' => 0,'message'=>'文件過大，推薦圖片大小：2M'));
                    }
                    $realPath = $file->getRealPath();   //臨時文件的絕對路徑
                    $type = $file->getClientMimeType();     // image/jpeg
                    // 上傳文件
                    $filename = date('YmdHis') . '-' . uniqid() . '.' . $ext;
                    // 將圖片URL保存到數據庫                                    
                    $data['img_url'] = '/uploads/picture/'.$filename;
                    
                    // 使用我們新建的uploads本地存儲空間（目錄）
                    $bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
                    if($bool!=true){
                        return json_encode(array('status' => 0, 'message'=>'圖片上傳失敗'));
                    }
                    // else{
                    //     return json_encode(array('status' => 1, 'message'=>'圖片上傳成功'));
                    // }
                }                       
            }else{
                return json_encode(['status' => 0, 'message'=>'請選擇要上傳的圖片']);
            }
            $data['name'] = trim($info['name']);
            $data['desc'] = trim($info['desc']);
            $data['is_show'] = intval($info['is_show']);
            $save = CommonModel::updateData('picture',['id'=>$id],$data);
            if($save == true || $bool==true){
                return json_encode(['status' => 1, 'message'=>'修改成功','jumpUrl'=>$this->redirectTo]);
            }else{
                return json_encode(['status' => 0, 'message'=>'修改失敗']);
            }

        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    // 刪除圖片並且改變狀態
    public function dodel(Request $request)
    {
        if($request->isMethod('POST')){
            $idstr=$request->input('idstr');
            if($idstr != ''){
                $i = 0;
                $y = 0;
                $idarr = explode(",",$idstr);
                // dd(count($idarr));
                if(count($idarr)>1){
                    foreach ($idarr as $id) {
                        $res =CommonModel::delData('picture',['id'=>$id]);
                        if($res){
                            $i++;
                        }else{
                            $y++;
                        }
                    }
                    if($y == 0){
                        $info = CommonModel::getOne('picture',['id'=>$id]);
                        if( !empty($info->img_url) || !file_exists($info->img_url) ){
                            @unlink(public_path() . $info->img_url);
                        }
                        return response()->json(array('status' => 1,'message'=>'刪除成功'));
                    }elseif($i == 0){
                        return response()->json(array('status' => 0,'message'=>'刪除失敗'));
                    }else{
                        return response()->json(array('status' => 2,'message'=>'有'.$i.'條刪除成功，有'.$y.'條刪除失敗'));
                    }
                }else{

                    $res =CommonModel::delData('picture',['id'=>$idarr[0]]);
                    // return response()->json(DB::getQueryLog());
                    // $queries = DB::getQueryLog();
                    // dd($res);
                    if($res){
                        $info = CommonModel::getOne('picture',['id'=>$id]);
                        if( !empty($info->img_url) || !file_exists($info->img_url) ){
                            @unlink(public_path() . $info->img_url);
                        }
                        return response()->json(array('status' => 1,'message'=>'刪除成功'));
                    }else{
                        return response()->json(array('status' => 0,'message'=>'刪除失敗'));
                    }
                }
                
                
            }
        }
    }






}
